<?php

namespace App\Service\College;


use App\Models\College\CollegeCourseModel;
use App\Models\College\CollegeCourseProgressModel;
use App\Models\College\CollegeTrainingOrderModel;
use App\Models\Common\ConfigModel;
use App\Models\Common\ResourcesModel;
use App\Service\BaseService;
use Illuminate\Support\Facades\DB;


class CollegeCourseService extends BaseService
{
    /**
     * 获得课程列表
     * @param int $userId
     * @param string $name
     * @return array
     */
    public static function getCourseList(int $userId, string $name)
    {
        $list = CollegeCourseModel::query()
            ->where('status', CollegeCourseModel::COURSE_STATUS_ON)
            ->when(mb_strlen($name), function ($query) use ($name) {
                $query->where('name', 'like', "%{$name}%");
            })
            ->with([
                'resourcesRel',
                'categoryRel',
                'courseProgressRel' => function ($query) use ($userId) {
                    $query->where('userId', $userId);
                }
            ])
            ->get()
            ->map(function (CollegeCourseModel $collegeCourseModel) {
                //获得封面图
                $titlePage = collect($collegeCourseModel->resourcesRel)->where('name', 'coursesCoverImg')->pluck('url')->toArray(); //课程封面 （只展示一张）

                //判断用户是否已读
                $readRes = collect($collegeCourseModel->courseProgressRel)->pluck('courseId')->toArray();
                return [
                    'titlePage'       => picturePath($titlePage[0] ?? '6b/b3/7111ae4f1ba228d01480919ffc10107456949cff274517a520d9c7c39deb.jpeg'),  //todo  默认封面图片
                    'name'            => $collegeCourseModel->name,
                    'isRead'          => in_array($collegeCourseModel->id, $readRes) ? '已读' : '未读',
                    'coursewareCount' => $collegeCourseModel->resourcesRel->count() - count($titlePage),
                    'id'              => $collegeCourseModel->id,
                    'type'            => CollegeCourseModel::TYPE_MAPPING[$collegeCourseModel->type] ?? '',
                    'classify'        => $collegeCourseModel->categoryId,
                ];
            })->toArray();
        return [
            'list'     => $list,
            'classify' => CategoryService::getCategoryList(),
        ];
    }

    /**
     * 根据课程ID和商家ID获得课程详情
     * @param int $userId
     * @param $id
     * @return array
     */
    public static function getCourseDetail(int $userId, $id)
    {
        //新加数据
        $collegeCourseProgressModel = CollegeCourseProgressModel::query()->firstOrNew([
            'courseId'   => $id,
            'userId'     => $userId,
            'resourceId' => 0
        ]);
        $collegeCourseProgressModel->save();

        $collegeCourseModel = CollegeCourseModel::query()
            ->where('id', $id)
            ->with([
                'resourcesRel',
                'categoryRel',
                'courseProgressRel' => function ($query) use ($userId) {
                    $query->where('userId', $userId)->where('resourceId', '>', 0);
                }
            ])
            ->first();

        if (null == $collegeCourseModel || $collegeCourseModel->status == CollegeCourseModel::COURSE_STATUS_OFF) {
            self::throwErr('该课程不存在或已下架');
        }

        //获得封面图
        $titlePage = collect($collegeCourseModel->resourcesRel)->where('name', 'coursesCoverImg')->pluck('url')->toArray(); //课程封面 （只展示一张）

        //获取各资源的学习时长
        $courseProgress = array_column($collegeCourseModel->courseProgressRel->toArray(), null, 'resourceId');

        $coursewareList = [];
        collect($collegeCourseModel->resourcesRel)->each(function (ResourcesModel $resourcesModel) use ($courseProgress, &$coursewareList) {
            $baseInfo = (array)json_decode($resourcesModel->extra, true);
            if ($resourcesModel->name != 'coursesCoverImg') {  //获得非封面图的（课件）
                $coursewareList[] = [
                    'id'            => $courseProgress[$resourcesModel->id]['id'] ?? 0,
                    'name'          => $baseInfo['name'] ?? '-',
                    'duration'      => $baseInfo['duration'] ?? 0,
                    'learned'       => $courseProgress[$resourcesModel->id]['finishRate'] ?? 0,
                    'type'          => $baseInfo['type'] ?? '-',
                    'finishSeconds' => $courseProgress[$resourcesModel->id]['finishSeconds'] ?? 0,
                    'resource'      => picturePath($resourcesModel->url),
                    'resourceId'    => $resourcesModel->id,
                ];
            }
        })->toArray();
        return [
            'id'              => $collegeCourseModel->id,
            'titlePage'       => picturePath($titlePage[0] ?? '6b/b3/7111ae4f1ba228d01480919ffc10107456949cff274517a520d9c7c39deb.jpeg'),
            'name'            => $collegeCourseModel->name,
            'classify'        => (string)optional($collegeCourseModel->categoryRel)->name,
            'coursewareCount' => $collegeCourseModel->resourcesRel->count() - count($titlePage),
            'desc'            => $collegeCourseModel->desc,
            'coursewareList'  => array_values($coursewareList),
        ];
    }

    /**
     * 根据秒转变为时分秒  1 => 00:00:01
     * @param $seconds
     * @return string
     */
    public static function changeTimeType($seconds): string
    {
        $seconds = intval($seconds);
        if ($seconds > 3600) {
            $hours = intval($seconds / 3600);
            $time  = $hours . ":" . gmstrftime('%M:%S', $seconds);
        } else {
            $time = gmstrftime('%H:%M:%S', $seconds);
        }
        return $time;
    }

    /**
     * 更新学习进度
     * @param int $id
     * @param int $resourceId
     * @param int $seconds
     * @param int $userId
     * @return void
     */
    public static function updateProgress(int $id, int $resourceId, int $seconds, int $userId)
    {
        //根据资源ID获得资源长度
        $resourceModel = ResourcesModel::query()->find($resourceId);
        if (null == $resourceModel) {
            self::throwErr('该资源已失效');
        }
        $duration = ((array)json_decode($resourceModel->extra, true))['duration'] ?? 0;
        if (!$duration) {
            self::throwErr('该资源无学习进度');
        }

        //修改课程资源学习进度
        $collegeCourseProgressModel                = CollegeCourseProgressModel::query()->firstOrNew(['courseId' => $id, 'resourceId' => $resourceId]);
        $finishRate = floor($seconds / $duration * 100);
        if (!$collegeCourseProgressModel->id) {
            $collegeCourseProgressModel->finishRate    = $finishRate; //学习进度
            $collegeCourseProgressModel->totalSeconds  = $duration;
            $collegeCourseProgressModel->finishSeconds = $seconds;
            $collegeCourseProgressModel->userId        = $userId;
            $collegeCourseProgressModel->save();
        } else {
            CollegeCourseProgressModel::query()->where('id', $collegeCourseProgressModel->id)
                ->where('finishRate', '<', $finishRate)
                ->update([
                    'finishSeconds' => $seconds,
                    'finishRate'    => $finishRate,
                ]);
        }
    }

    /**
     * 校区信息
     * @return array
     */
    public static function campusInfo(): array
    {
        return ConfigModel::getValueNewJson('college', 'college-campus-info', 600);
    }
}
